package com.qiu.greened.data

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.qiu.greened.bean.ReplyBean
import com.qiu.greened.bean.ReplyPostBean
import com.qiu.greened.network.PostService
import com.qiu.greened.network.UserService
import com.qiu.greened.utils.MyData.Companion.token
import com.qiu.greened.utils.showToast

/**
 * 定义分页数据的数据源,以及从该数据源获取数据的方式
 */
class NotificationsReplyPagingSource(private val userService: UserService, private val  userId: Int): PagingSource<Int, ReplyBean>() {
    override fun getRefreshKey(state: PagingState<Int, ReplyBean>): Int? {
//        return state.anchorPosition
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ReplyBean> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
            val postList = userService.getReply(token, userId, page, pageSize).dataConvert()
//            postList.toString().showToast()
            val prevKey = if (page > 1) page - 1 else null
            val nextKey = if (postList.isNotEmpty()) page + 1 else null
            LoadResult.Page(postList, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}